<template>
	<view class="authen-content">
		<u-form :model="safeForm" ref="uForm" label-width="30%">
			<u-form-item label="真实姓名" prop="name">
				<u-input v-model="safeForm.name" placeholder="请填写" />
			</u-form-item>
			<u-form-item label="身份证号" prop="idCard">
				<u-input v-model="safeForm.idCard" placeholder="请填写" />
			</u-form-item>
		</u-form>
		<u-button @click="nextSubmit" :custom-style="buttonStyle" shape="circle" hover-class="none">下一步</u-button>
		<!-- <u-modal v-model="successShow" title="验证成功" :title-style="{fontWeight:700}" width="80%" :show-confirm-button="false"
			confirm-text="去认证" :content-style="contentStyle2">
			<view class="slot-content">
				<rich-text nodes="下一步将进入职业认证或可选择跳过"></rich-text>
				<view class="modal-button">
					<view :style="cancelStyle2" @click="closeModal">跳过</view>
					<view :style="confirmStyle2" @click="toCertification">下一步</view>
				</view>
			</view>
		</u-modal> -->
	</view>
</template>

<script>
	import {
		API
	} from "@/config/myApi.js";
	import {
		realName,
		checkIdCard,
		idCard
	} from "@/utils/RegExp.js";
	const n = uni.requireNativePlugin('AP-FaceDetectModule');
	export default {
		data() {
			return {
				duration: this.$store.state.toastDuration,
				safeForm: {
					name: '',
					idCard: '',
				},
				certifyId: null, //认证ID
				rules: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur',
					}, {
						pattern: realName,
						// 正则检验前先将值转为字符串
						transform(value) {
							return String(value);
						},
						message: '姓名至少要2个字符',
						trigger: 'blur',
					}],
					idCard: [{
							required: true,
							message: '请输入身份证号',
							trigger: 'blur',
						},
						{
							pattern: idCard,
							// 正则检验前先将值转为字符串
							transform(value) {
								return String(value);
							},
							message: '身份证格式不正确',
							trigger: 'blur',
						},
						// {
						// 	asyncValidator: (rule, value, callback) => {
						// 		console.log(value, rule);
						// 		/*表单验证*/
						// 		if (!value) {
						// 			callback("身份证号码为不能为空");
						// 		} else if (typeof this.checkIdCard(value, rule) != "boolean") {
						// 			callback("身份证号码格式错误");
						// 		} else {
						// 			callback();
						// 		}
						// 	}
						// },
					],
				},
				// 下一步
				buttonStyle: {
					width: "100%",
					color: "#fff",
					fontSize: "32rpx",
					backgroundColor: "#F4333C",
				},
				// 模态框
				successShow: false,
				// 内容样式
				contentStyle2: {
					height: "80rpx",
					marginTop: "50rpx",
					marginBottom: "180rpx",
					color: "#666666",
					fontSize: "30rpx",
					fontWeight: "500",
					lineHeight: "80rpx",
					textAlign: "center"
				},
				// 取消样式
				cancelStyle2: {
					width: "32%",
					height: "80rpx",
					fontSize: "30rpx",
					fontWeight: "bold",
					lineHeight: "80rpx",
					backgroundColor: "#ECECEC",
					borderRadius: "40rpx",
				},
				// 确认样式
				confirmStyle2: {
					width: "32%",
					height: "80rpx",
					color: "#fff",
					fontSize: "30rpx",
					fontWeight: "bold",
					lineHeight: "80rpx",
					backgroundColor: "#F4333C",
					borderRadius: "40rpx",
				},
			};
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onUnload() {
			this.safeForm = {
				name: '',
				idCard: ''
			}
		},
		onBackPress(e) {
			if (e.from == "backbutton") {
				uni.$emit("toBack", true)
			}
		},
		methods: {
			// 发起认证请求
			getInitFaceVerify() {
				try {
					const params = {
						certName: this.safeForm.name,
						certNo: this.safeForm.idCard,
						certType: "IDENTITY_CARD",
						metaInfo: n.getMetaInfo() ,
						model: "MULTI_ACTION",
						productCode: "ID_PRO",
					}
					console.log("发起请求：", params);
					API.initFaceVerify(params).then(res => {
						console.log('res','请求后端的接口结果',res)
						if (res.success && res.result) {
							this.certifyId = res.result.resultObject.certifyId;
							// uni.showToast({
							// 	title: res.result.message,
							// 	icon: "none",
							// 	duration: 2000
							// })
							this.verifyC();
						} else {
							uni.showToast({
								title: res.message,
								icon: "none"
							})
						}
						console.log('发起认证请求1:', res)
					}).catch(err => {
						console.log('err接口请求失败',err)
					})
				} catch(err) {
					console.log(err)
				}
				
			},
			// 人脸验证
			verifyC() {
				let _this = this;
				console.log('this.certifyId',this.certifyId)
				n.verify({
						certifyId: this.certifyId, //认证ID
						returnVideo: false, //是否返回视频（iOS）
						returnVideoUpload: false, //是否需要将返回视频上传到OSS（iOS）
						ext_params_key_use_video: false, //是否返回视频并上传到OSS（Android）
					},
					function(v) {
						console.log('离线验证：', v)
						// 有效验证，需向服务端验证结果
						if (v.code == 1000 || v.code == 2006) { //1000成功 2006失败
							// _this.serverVerify(); //暂时注释
							if (v.code == 1000) {
								// _this.successShow = true;
								uni.setStorageSync('successVerifyCInfo', _this.safeForm)
								_this.sendResult();
							} else {
								uni.showToast({
									title: '验证未通过',
									icon: 'none',
									duration: _this.duration
								});
							}
						} else {
						const codeMsg = [
							{code: 1001,msg: '系统错误'},
							{code: 1003,msg: '验证中断'},
							{code: 2002,msg: '网络错误'},
							{code: 2003,msg: '客户端设备时间错误'},
							{code: 2006,msg: '刷脸失败'},
							
						]
						 if(v.code === 1001) {
							uni.showToast({
							  title: '身份信息错误',
							  position: "top",
							  duration: _this.duration
							});
							return
						  }
							// 1001 系统错误
							uni.showToast({
								title: codeMsg.find(it=>it.code === v.code)?.msg || v.code,
								duration: 2000,
								position: "top",
								duration: _this.duration
							});
						}
					}
				);
			},
			// 向服务端再次验证结果
			serverVerify() {
				let params = {
					certifyId: this.certifyId
				};
				API.verifyResult(params).then(res => {
					// uni.showToast({
					// 	title:"verifyResult",
					// 	duration:2000,
					// })
					console.log('向服务端再次验证结果：', res)
				}).catch(err => {
					console.log('向服务端再次验证结果',err)
				})
			},
			// 向后端通知验证结果
			sendResult() {
				let params = {
					realName: this.safeForm.name,
					idCard: this.safeForm.idCard,
				}
				API.postSendResult(params).then(res => {
					if (res.success) {
						uni.showToast({
							title: '认证成功',
							icon: "none",
							duration: 2000,
							success() {
								setTimeout(() => {
									// uni.navigateBack();
									uni.$emit("toBack", true)
									console.log("离开页面")
									uni.showToast({
										title: '验证成功,即将跳转下一页',
										duration: 2000,
										success: () => {
											uni.redirectTo({
												url: "/pages/passport/certification/professionalVerification" // 去职业认证
											})
										}
									});
								}, 2000)
							}
						})
					}
				});
			},
			// 下一步
			nextSubmit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('已填写信息')
						this.getInitFaceVerify();
					}
				});
			},
			// 关闭模态框
			closeModal() {
				this.successShow = false;
				uni.switchTab({
					url: "/pages/tabbar/home/index" // 去首页
				})
			},
			// 确认
			toCertification() {
				uni.navigateTo({
					url: "/pages/passport/certification/professionalVerification" // 去职业认证
				})
				this.successShow = false;
			}
		}


	}
</script>

<style lang="scss" scoped>
	.authen-content {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 100%;
		padding: 70rpx 70rpx;
		background-color: #fff;
	}

	// 模态框
	.slot-content {
		.modal-button {
			margin-top: 50rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
		}
	}
</style>
